<html>
<body>
<h1>JS变速齿轮DEMO</h1>
<h2>速度增量：<span id="speed"></span></h2>
<button onclick="dec_speed();">减速</button>
<button onclick="add_speed();">加速</button>
<br>
LOG：<br>
<textarea id="log" style="width: 500px; height: 200px;"></textarea>
<div id="box" style="margin: 10px; position: absolute; width: 90px; height: 90px; background: #00ffff; border-radius: 50px;"></div>
<script>
    //变速增量
    var speed = 0;
    document.getElementById("speed").innerHTML = speed;
    //Hook setTimeut，实现变速
    //备份原始setTimeout函数
    var pre_setTimeout = setTimeout;
    //新的setTimeout函数
    var setTimeout = function(){
        arguments[1] = arguments[1] + speed;
        console.log("arguments", arguments[1]);
//最小为1，1毫秒
        if(arguments[1]<1) arguments[1] = 1;
//执行回调函数
        pre_setTimeout.apply(this, arguments);
    }
    //加速
    function add_speed(){
        speed = speed - 20;
        console.log("速度",speed);
        document.getElementById("log").innerHTML += (new Date).toGMTString() + " 速度:" + (-speed) + "\n";
        if(speed < -100) speed = -100
        document.getElementById("speed").innerHTML = -speed;
    }
    //减速
    function dec_speed(){
        speed += 20;
        console.log("速度",speed)
        document.getElementById("log").innerHTML += (new Date).toGMTString() + " 速度:" + (-speed) + "\n";
        if(speed > 200) speed = 200
        document.getElementById("speed").innerHTML = -speed;
    }
    //小球移动动画
    function move() {
        var box = document.getElementById("box");
        var current_position = 0;
        var left = 1;
//循环调用
        function render() {
            setTimeout(render, 100);
            current_position += left;
            if (current_position == 200 || current_position == 0){
                left = -left;
            }
            box.style.left = current_position + "px";
        }
        render();
    }
    move();
</script>
</body>
</html>